-
Notifications
You must be signed in to change notification settings - Fork 18
feat(svg): adds sprite hash manifest for cache busting #471
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
Reviewer's GuideAdds a Webpack plugin that generates a JSON manifest of content hashes for SVG sprite files and updates the Svg service to read this manifest and append a cache-busting query parameter to sprite URLs. Sequence diagram for Webpack build generating sprite-hashes.jsonsequenceDiagram
participant WebpackCompiler
participant SpriteHashPlugin
participant FileSystem
WebpackCompiler->>SpriteHashPlugin: trigger afterEmit hook
SpriteHashPlugin->>FileSystem: exists(spriteDir)
alt spriteDir does not exist
SpriteHashPlugin-->>WebpackCompiler: log warning and callback
else spriteDir exists
SpriteHashPlugin->>FileSystem: readDir(spriteDir)
FileSystem-->>SpriteHashPlugin: list svgFiles
loop for each svgFile
SpriteHashPlugin->>FileSystem: readFile(filePath)
FileSystem-->>SpriteHashPlugin: svgContent
SpriteHashPlugin->>SpriteHashPlugin: compute md5 hash
SpriteHashPlugin->>SpriteHashPlugin: store relativePath -> hash
end
SpriteHashPlugin->>FileSystem: writeFile(outputFile, hashesJson)
FileSystem-->>SpriteHashPlugin: write complete
SpriteHashPlugin-->>WebpackCompiler: callback
end
Sequence diagram for Svg service resolving sprite URL with hashsequenceDiagram
participant Template
participant Svg as SvgService
participant FileSystem
Template->>Svg: get_the_icon(icon_class, additionnal_classes)
Svg->>Svg: normalize icon_class to icon_slug
Svg->>Svg: build css classes
Svg->>Svg: get_sprite_hash(sprite_name)
Svg->>FileSystem: get_theme_file_path(sprite_hash_file)
Svg->>FileSystem: is_readable(sprite_hash_file)
alt sprite-hashes.json not readable
Svg-->>Svg: return empty hash string
else readable
Svg->>FileSystem: file_get_contents(sprite_hash_file)
FileSystem-->>Svg: jsonContent
Svg->>Svg: json_decode(jsonContent)
alt hash for sprite exists
Svg-->>Svg: return ?hash
else missing hash
Svg-->>Svg: return empty hash string
end
end
Svg->>Svg: build spriteUrl with optional hash
Svg-->>Template: svg markup with use href spriteUrl#icon_slug
Class diagram for SpriteHashPlugin and updated Svg serviceclassDiagram
class SpriteHashPlugin {
+object options
+SpriteHashPlugin(options)
+apply(compiler)
}
class Svg {
+get_the_icon(icon_class, additionnal_classes)
+allow_svg_tag(tags)
+get_sprite_hash(sprite_name)
}
class FileSystem {
+readFile(path)
+writeFile(path, content)
+readDir(path)
+exists(path)
}
SpriteHashPlugin ..> FileSystem : uses
Svg ..> FileSystem : uses
Flow diagram for build and runtime usage of sprite hash manifestflowchart LR
subgraph Build
A["Webpack build"] --> B["SpriteHashPlugin afterEmit"]
B --> C["Compute hashes for dist/icons svg files"]
C --> D["Write dist/sprite-hashes.json"]
C --> E["Output dist/icons sprite svg files"]
end
subgraph Runtime
F["Theme templates call Svg service"] --> G["Svg.get_sprite_hash reads sprite-hashes.json"]
G --> H["Svg.get_the_icon builds sprite url with ?hash"]
H --> I["Browser requests dist/icons sprite.svg?hash"]
end
D --> G
E --> I
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey - I've left some high level feedback:
- In
Svg::get_sprite_hash, the JSON file is read and decoded on every call; consider caching the decoded hash map in a property (or memoizing per request) to avoid repeated disk I/O and JSON parsing when many icons are rendered on a page. - The key used for lookup in
get_sprite_hash(sprintf('icons/%s.svg', $sprite_name)) is duplicated multiple times; computing it once and reusing the variable would simplify the logic and reduce the chance of typos if the format changes. - The webpack
SpriteHashPluginusesconsole.log/console.warnand synchronous fs calls insideafterEmit.tapAsync; consider switching tocompiler.getInfrastructureLoggerfor logging and wrapping fs operations in try/catch with propercallback(err)handling to avoid noisy output or silent failures in builds.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `Svg::get_sprite_hash`, the JSON file is read and decoded on every call; consider caching the decoded hash map in a property (or memoizing per request) to avoid repeated disk I/O and JSON parsing when many icons are rendered on a page.
- The key used for lookup in `get_sprite_hash` (`sprintf('icons/%s.svg', $sprite_name)`) is duplicated multiple times; computing it once and reusing the variable would simplify the logic and reduce the chance of typos if the format changes.
- The webpack `SpriteHashPlugin` uses `console.log`/`console.warn` and synchronous fs calls inside `afterEmit.tapAsync`; consider switching to `compiler.getInfrastructureLogger` for logging and wrapping fs operations in try/catch with proper `callback(err)` handling to avoid noisy output or silent failures in builds.Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Implements a webpack plugin that generates a JSON file containing content hashes for SVG sprite files. This allows for cache busting of sprite files by appending the hash as a query parameter to the sprite URL. The `Svg` service is updated to read the hash from the generated JSON and append it to the sprite URL.
27f53ba to
4ee0928
Compare
|
@firestar300 ça peut-être implémenté sur les projets en cours ? |
Oui mais attention non compatible avec le bloc icône. C'est surtout pour les services C'est encore mieux si tu peux l'intégrer sur un projet et faire des retours si tu vois des bugs. |
| */ | ||
| formatPhpArray(obj) { | ||
| const entries = Object.entries(obj).map(([key, value]) => { | ||
| const escapedKey = key.replace(/'/g, "\\'") |
Check failure
Code scanning / CodeQL
Incomplete string escaping or encoding High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI about 4 hours ago
In general, when building string literals with manual escaping, backslashes must be escaped before escaping other meta-characters like single quotes. For PHP single-quoted strings, every backslash (\) should become \\, and every single quote (') should become \'.
The best fix here is to replace the ad-hoc replace(/'/g, "\\'") logic with a small helper that correctly escapes both backslashes and single quotes for PHP single-quoted strings. This helper should be used for both keys and values in formatPhpArray. The order of replacements matters: first replace \ with \\, then replace ' with \', so that newly added backslashes from the quote-escaping step are not re-escaped.
Concretely, in config/webpack-sprite-hash-plugin.js:
- Add a private helper method (e.g.,
_escapePhpSingleQuoted) to theSpriteHashPluginclass, aboveformatPhpArray. - Implement it as
return String(str).replace(/\\/g, '\\\\').replace(/'/g, "\\'"). - Update
formatPhpArrayto use this helper for bothkeyandvalueinstead of the current.replace(/'/g, "\\'")calls.
No new imports are needed; only standard JavaScript string methods and regexes are used.
-
Copy modified lines R26-R35 -
Copy modified lines R43-R44
| @@ -23,6 +23,16 @@ | ||
| } | ||
|
|
||
| /** | ||
| * Escapes a string for safe use inside a PHP single-quoted string literal. | ||
| * | ||
| * @param {string} str Input string. | ||
| * @return {string} Escaped string. | ||
| */ | ||
| _escapePhpSingleQuoted(str) { | ||
| return String(str).replace(/\\/g, '\\\\').replace(/'/g, "\\'") | ||
| } | ||
|
|
||
| /** | ||
| * Formats a plain object as a PHP associative array string. | ||
| * | ||
| * @param {Record<string, string>} obj Key-value pairs. | ||
| @@ -30,8 +40,8 @@ | ||
| */ | ||
| formatPhpArray(obj) { | ||
| const entries = Object.entries(obj).map(([key, value]) => { | ||
| const escapedKey = key.replace(/'/g, "\\'") | ||
| const escapedValue = String(value).replace(/'/g, "\\'") | ||
| const escapedKey = this._escapePhpSingleQuoted(key) | ||
| const escapedValue = this._escapePhpSingleQuoted(value) | ||
| return `\t'${escapedKey}' => '${escapedValue}'` | ||
| }) | ||
| return `array(\n${entries.join(',\n')}\n)` |
| formatPhpArray(obj) { | ||
| const entries = Object.entries(obj).map(([key, value]) => { | ||
| const escapedKey = key.replace(/'/g, "\\'") | ||
| const escapedValue = String(value).replace(/'/g, "\\'") |
Check failure
Code scanning / CodeQL
Incomplete string escaping or encoding High
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI about 4 hours ago
To correctly encode strings for a PHP single-quoted literal, both backslashes and single quotes must be escaped. In PHP, this is done by replacing \ with \\ and ' with \' (in that order). The current implementation only escapes single quotes with replace(/'/g, "\\'"), leaving backslashes unchanged, which can break the intended escaping if the original value contains backslashes.
The best fix is to update the formatPhpArray method so that it first escapes backslashes, then escapes single quotes, for both keys and values. We keep the current structure and behavior, only improving the escaping. Concretely, in config/webpack-sprite-hash-plugin.js, lines 33–35 inside formatPhpArray should be changed so that:
escapedKeyis computed with.replace(/\\/g, '\\\\').replace(/'/g, "\\'")escapedValueis computed similarly with.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
No new imports or methods are necessary; this uses only built-in string operations. All other behavior (file paths, hash generation, output file format) remains unchanged.
-
Copy modified lines R33-R34
| @@ -30,8 +30,8 @@ | ||
| */ | ||
| formatPhpArray(obj) { | ||
| const entries = Object.entries(obj).map(([key, value]) => { | ||
| const escapedKey = key.replace(/'/g, "\\'") | ||
| const escapedValue = String(value).replace(/'/g, "\\'") | ||
| const escapedKey = key.replace(/\\/g, '\\\\').replace(/'/g, "\\'") | ||
| const escapedValue = String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'") | ||
| return `\t'${escapedKey}' => '${escapedValue}'` | ||
| }) | ||
| return `array(\n${entries.join(',\n')}\n)` |
Implements a webpack plugin that generates a JSON file containing content hashes for SVG sprite files.
This allows for cache busting of sprite files by appending the hash as a query parameter to the sprite URL.
The
Svgservice is updated to read the hash from the generated JSON and append it to the sprite URL.{ "icons/social.svg": "75b76133", "icons/sprite.svg": "95c11cc9" }Summary by Sourcery
Add cache-busting support for SVG sprite icons using a generated hash manifest.
New Features:
Enhancements: